//
//  CustomLayout.m
//  15-homework-Customlayout-wangyi
//
//  Created by 王道林 on 16/8/3.
//  Copyright © 2016年 王道林. All rights reserved.
//

#import "CustomLayout.h"

@interface CustomLayout ()
@property (nonatomic, assign) CGFloat contentWidth;
@property (nonatomic, assign) CGFloat contentHeight;
@property (nonatomic, assign) CGFloat lastHeight;
@property (nonatomic, strong) NSMutableArray<UICollectionViewLayoutAttributes *> *marrAttribute;
@property (nonatomic, assign) CGFloat collectionWidth;

@end

@implementation CustomLayout


- (instancetype)init
{
    self = [super init];
    if (self) {
        _sectionInsert = 10;
        _marrAttribute = [NSMutableArray array];
    }
    return self;
}

- (CGFloat)collectionWidth
{
    return CGRectGetWidth(self.collectionView.frame);
}


- (void)prepareLayout
{

    // 记录width
    _contentWidth = _sectionInsert;
    _contentHeight = _sectionInsert;
    if (_marrAttribute.count != 0) {
        [_marrAttribute removeAllObjects];
    }
    
    for (int i = 0; i < [self.collectionView numberOfItemsInSection:0]; i++) {
    
        UICollectionViewLayoutAttributes *layoutAttributes = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:[NSIndexPath indexPathForRow:i inSection:0]];
        CGSize size = [self.delegate collectionView:self.collectionView layout:self sizeForItemAtIndexPath:[NSIndexPath indexPathForRow:i inSection:0]];
        CGFloat backheight = size.height;
        CGFloat backwidth = size.width;
        if (_contentWidth + backwidth < self.collectionWidth) {
            CGFloat x = _contentWidth;
            CGFloat y = _contentHeight;
            CGFloat width = backwidth;
            CGFloat height = backheight;
            
            layoutAttributes.frame = CGRectMake(x, y, width, height);
            [_marrAttribute addObject:layoutAttributes];
            _contentWidth = x + width + _sectionInsert;
            _lastHeight = backheight;
        } else if (_contentWidth + backwidth > self.collectionWidth)
        {
            _contentWidth = _sectionInsert;
            _contentHeight = _contentHeight + _lastHeight +_sectionInsert;
            CGFloat x = _contentWidth;
            CGFloat y = _contentHeight;
            CGFloat width = backwidth;
            CGFloat height = backheight;
            
            layoutAttributes.frame = CGRectMake(x, y, width, height);
            [_marrAttribute addObject:layoutAttributes];
            _contentWidth = x + width + _sectionInsert;
            _lastHeight = backheight;
        }
    
    }
    
    _contentHeight = _contentHeight + _lastHeight;
  
}


- (NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect
{
    return _marrAttribute;
}
    


- (CGSize)collectionViewContentSize
{
    return CGSizeMake(self.collectionWidth, _contentHeight);
}



@end
